require "state_machine"

class PaperRequireRepo < Sequel::Model(:paper_require)
  plugin :validation_helpers
  many_to_one :paper_type, class: "PaperTypeRepo"
  many_to_one :manager,    class: "ManagerRepo"
  
  def validate
    super
    validates_unique   [:manager_id, :position_id, :paper_type_id]
    validates_presence [:manager_id, :position_id, :paper_type_id]
  end


  def perfect
    position = PositionRepo[position_id]
    {
      id: id,
      manager:  {id: manager.id,  name: manager.name},
      position: {id: position.id, name: position.name},
      paper_type:  {id: paper_type.id, name: paper_type.name}
    }
  end

    
  
  def self.group(manager_id, position_id)
    result = PaperRequireRepo.where(manager_id: manager_id, position_id: position_id)

    manager = ManagerRepo[manager_id]
    position = PositionRepo[position_id]
    
    {
      manager:  {id: manager_id,  name: manager.name},
      position: {id: position_id, name: position.name},
      paper_types: result.map do |e|
        {require_id: e.id, id: e.paper_type.id, name: e.paper_type.name}
      end
    }
  end
end
